// 封装线程库
#pragma once
#include <cassert>
#include <iostream>
#include <string>
#include <functional>
#include <pthread.h>
#include <memory>
using namespace std;
#define NUM 1024

typedef function<void *(void *)> func_t;
class Thread;//声明
class Contex//上下文
{
public:
    Contex()
        : _this(nullptr)
    {}

public:
    Thread *_this;
};
class Thread
{
public:
    Thread(const func_t func , void *args = nullptr)
        : _func(func) , _args(args)
    {
        char namebuffer[NUM];
        snprintf(namebuffer, sizeof namebuffer, "thread-%d", _num++);
        _name = namebuffer;
    }
    string &threadName()
    {
        return _name;
    }
    static void *start_routine(void *args) // 静态方法不能调用成员函数或者成员变量
    {
        Contex* ctx = static_cast<Contex*>(args);
        void* ret = ctx->_this->run();
        delete ctx;
        return ret;
    }
    void start()
    {
        Contex* ctx = new Contex();//利用该结构体对象传递参数
        ctx->_this = this;
        int ret = pthread_create(&_tid, nullptr, start_routine, (void*)ctx);
        assert(ret == 0);
        (void)ret;
    }
    void join()
    {
        int ret = pthread_join(_tid , nullptr);
        assert(ret == 0);
        (void)ret;
    }
    ~Thread()
    {
        //do nothing
    }
private:
    void* run()
    {
        return _func(_args);
    }
private:
    pthread_t _tid;
    string _name;
    void *_args;
    static int _num;

    func_t _func;//该参数的目的是模拟之前调用pthread_create时，执行其他函数的功能
};
int Thread::_num = 1; // 静态成员可以在类外定义